
const { User } = require("../db");
const axios = require('axios');
const jwt = require('jsonwebtoken');
const { secretKey } = require('../config/config');
const APPID = 'wx4abf7dc46f46fd7b';
const SECRET = '38553c5e31f2fab93143fb7ef865e291';
async function getOpenId(code) {
    const response = await axios.get(`https://api.weixin.qq.com/sns/jscode2session`, {
        params: {
            appid: APPID,
            secret: SECRET,
            js_code: code,
            grant_type: 'authorization_code'
        }
    });
    return response.data;
}

exports.loginWX = async (req, res) => {
    const { code } = req.body;
    if (code) {
        try {
            const { openid } = await getOpenId(code);
            const tempUser = await User.findOne({ where: { openId: openid } });
            if (!tempUser) {
                // 如果不存在该用户，则随机新建
                const userinfo = User.create({
                    openId: openid, username: '微信用户' + Math.floor(Math.random() * 1000000),
                    password: '123456', avatarUrl: 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_1280.png',
                    postNums: 0
                });
                const tokenStr = jwt.sign({ id: tempUser.dataValues.id, username: userinfo.username }, secretKey, { expiresIn: '11130s' })
                res.send({
                    status: 200,
                    message: '创建用户成功，登录成功！',
                    token: tokenStr, // 要发送给客户端的 token 字符串
                    user: tempUser.dataValues,
                    new: true
                })
            }
            else {
                const tokenStr = jwt.sign({ id: tempUser.dataValues.id }, secretKey, { expiresIn: '11130s' })
                res.send({
                    status: 200,
                    message: '登录成功！',
                    token: tokenStr, // 要发送给客户端的 token 字符串
                    user: tempUser.dataValues,
                    new: false
                })
            }
        } catch (error) {
            console.error(error);
            res.status(500).send('Failed to get openid');
        }
    } else {
        res.status(400).send('No code provided');
    }
};

exports.getUserInfo = async (req, res) => {
    console.log(req.user.id);
    const tempUser = await User.findOne({ where: { id: id } });

    res.send({
        status: 200,
        message: '获取用户信息成功！',
        user: tempUser.dataValues
    })
}

// 修改用户信息接口
exports.updateUserInfo = async (req, res) => {
    const { id } = req.user
    const { username, avatarUrl } = req.body;
    const tempUser = await User.findOne({ where: { id: id } });
    if (tempUser) {
        const newInfo = await User.update({ username: username || tempUser.dataValues.username, avatarUrl: avatarUrl || tempUser.dataValues.avatarUrl }, { where: { id: id } });

        if (newInfo[0] === 1)
            res.send({
                status: 200,
                message: '修改用户信息成功！',
            })
        else {
            res.send({
                status: 500,
                message: '修改用户信息失败！',
            })
        }
    }
}